package cn.lblbc.webbrowser.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.R
import cn.lblbc.webbrowser.models.HistoryItem

class AutoCompleteAdapter(
    private var historyItems: List<HistoryItem>,
    private val onItemClick: (HistoryItem) -> Unit
) : RecyclerView.Adapter<AutoCompleteAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val titleText: TextView = view.findViewById(R.id.suggestionTitle)
        val urlText: TextView = view.findViewById(R.id.suggestionUrl)
    }
    
    fun updateData(newHistoryItems: List<HistoryItem>) {
        historyItems = newHistoryItems
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_suggestion, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val historyItem = historyItems[position]
        holder.titleText.text = historyItem.title
        holder.urlText.text = historyItem.url
        holder.itemView.setOnClickListener { onItemClick(historyItem) }
    }

    override fun getItemCount() = historyItems.size
}